import socket
import threading
import re


class Server:
    def __init__(self):
        self.server = None
        self.port = 7890

    def tcp_init(self):
        # 创建套接字
        self.service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 确认端口复用
        self.service.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        #绑定端口
        self.service.bind(('', self.port))
        #监听套接字
        self.service.listen(128)
        while True:
            new_socket, client_addr = self.service.accept()
            #创建线程
            p = threading.Thread(target=self.tcp_client, args=(new_socket,))
            p.start()
        self.service.close()


    def tcp_client(self,new_socket:socket.socket):
        request = new_socket.recv(4096).decode('utf-8')
        print(request)
        request_list = request.splitlines()
        if request_list:
            file_name = ""
            ret = re.match(r"[^/]+(/[^ ]*)", request_list[0])
            if ret:
                file_name = ret.group(1)
                if file_name == "/":
                    file_name = "/index.html"

            try:
                f = open("./html" + file_name, "rb")  # 打开请求的资源
            except:  # 如果没有就返回404
                response = "HTTP/1.1 404 NOT FOUND\r\n"
                response += "\r\n"
                response += "------file not found-----"
                new_socket.send(response.encode("utf-8"))

            else:
                html_centent = f.read()
                f.close()
                response_boby = html_centent
                response = "HTTP/1.1 200 OK\r\n"
                response += "\r\n"
                # 发送response head发送给浏览器
                new_socket.send(response.encode('utf-8'))
                # 发送response boby给浏览器
                new_socket.send(response_boby)
        new_socket.close()



if __name__ == '__main__':
    tcp_server = Server()
    tcp_server.tcp_init()